<template>
  <el-select
    v-model="internalValue"
    :placeholder="placeholder"
    :filterable="filterable"
    :remote="remote"
    :multiple="multiple"
    :disabled="isDisabled"
    :loading="loading"
    :remote-method="handleRemoteSearch"
    @change="handleChange"
    popper-class="custom-remote-select-popper"
  >
    <template #default>
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
      <div v-if="options.length > 0" class="select-pagination">
        <button
          @click.stop="handlePageChange('prev')"
          :disabled="pagination.page <= 1 || loading"
          class="page-btn"
        >
          上一页
        </button>
        <span class="page-info">
          {{ pagination.page }} / {{ pagination.lastPage }}
        </span>
        <button
          @click.stop="handlePageChange('next')"
          :disabled="pagination.page >= pagination.lastPage || loading"
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </template>
  </el-select>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue';
import BaseApi from '@/api/admin/base.js';

const props = defineProps({
  modelValue: [String, Number, Array, Object],
  menuId: { type: Number, required: true },
  fieldName: { type: String, required: true },
  cascadeParams: { type: Object, default: () => ({}) },
  placeholder: { type: String, default: '请选择' },
  multiple: { type: Boolean, default: false },
  filterable: { type: Boolean, default: true },
  remote: { type: Boolean, default: true },
  disabled: { type: Boolean, default: false },
  // pageSize: { type: Number, default: 10 },
});

const emit = defineEmits(['update:modelValue', 'change']);

// 内部值，用于v-model
const internalValue = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

const options = ref([]);
const loading = ref(false);

// 分页状态
const pagination = reactive({
  page: 1,
  lastPage: 0,
  total: 0,
  query: '',
});

// 禁用状态：如果父组件传入 disabled 或级联参数不满足要求
const isDisabled = computed(() => {
  // 检查级联参数中是否有空值，如果有，则禁用
  const hasEmptyCascade = Object.values(props.cascadeParams).some(
    (val) => val === null || val === undefined || val === '',
  );
  return props.disabled || hasEmptyCascade;
});

// --- 核心数据请求逻辑 ---

/**
 * 通用选项数据请求函数
 * @param {boolean} isNewSearch - 是否为新的搜索/首次加载/级联重置
 */
const fetchOptionsData = async (isNewSearch = false) => {
  if (loading.value || isDisabled.value) return;

  const state = pagination;

  if (isNewSearch) {
    state.page = 1;
    options.value = []; // 搜索或首次加载时清空
  } else if (state.page > state.lastPage && state.lastPage !== 0) {
    return;
  }

  loading.value = true;

  const params = {
    menu_id: props.menuId,
    field_name: props.fieldName,
    page: state.page,
    // page_size: props.pageSize,
    query: state.query,
    cascade_params: JSON.stringify(props.cascadeParams),
  };

  try {
    const response = await BaseApi.getOptions(params);
    if (response.code === 200) {
      const data = response.data;
      options.value = data.list;
      state.total = data.total;
      state.lastPage = data.last_page;
      state.page = data.current_page;
    } else {
      console.error(
        `获取 ${props.fieldName} 选项失败:`,
        response.message || 'API 返回非 200 状态码',
      );
      if (!isNewSearch && state.page > 1) {
        state.page--;
      }
    }
  } catch (error) {
    console.error(`获取 ${props.fieldName} 选项异常:`, error);
    if (!isNewSearch && state.page > 1) {
      state.page--;
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 远程搜索方法
 * @param {string} query - 搜索关键字
 */
const handleRemoteSearch = (query) => {
  // 搜索时重置页码和选项，并设置新的查询关键字
  pagination.query = query;
  fetchOptionsData(true);
};

/**
 * 值改变事件
 */
const handleChange = (val) => {
  emit('change', val);
};

// --- 按钮分页逻辑 ---

const handlePageChange = async (direction) => {
  if (direction === 'prev' && pagination.page > 1) {
    pagination.page--;
    await fetchOptionsData(false);
  } else if (direction === 'next' && pagination.page < pagination.lastPage) {
    pagination.page++;
    await fetchOptionsData(false);
  }
};

// 当级联参数变化时，重置并重新加载数据
watch(
  () => props.cascadeParams,
  (newParams, oldParams) => {
    // 只有在级联参数发生实质性变化时才触发
    if (JSON.stringify(newParams) !== JSON.stringify(oldParams)) {
      // 清空当前值，防止选中值与新选项不匹配
      internalValue.value = props.multiple ? [] : null;

      // 重置分页状态和选项
      pagination.query = '';
      pagination.page = 1;
      options.value = [];

      // 如果级联参数有效，则重新加载数据
      if (!isDisabled.value) {
        fetchOptionsData(true);
      }
    }
  },
  { deep: true },
);

onMounted(() => {
  // 初始加载（如果不需要级联，或级联参数已满足）
  if (!isDisabled.value) {
    fetchOptionsData(true);
  }
});
</script>

<style lang="scss">
/* 必须使用 popper-class 才能在全局样式中选中下拉框 */
.custom-remote-select-popper {
  .select-pagination {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 8px 20px; /* 参照 el-option 的内边距 */
    border-top: 1px solid #e4e7ed; /* 添加一个分割线 */
    position: sticky; /* 让分页器始终固定在底部 */
    bottom: 0;
    background-color: #fff;
    z-index: 10; /* 确保在选项之上 */

    .page-btn {
      background-color: transparent;
      border: none;
      color: var(--el-color-primary); /* Element Plus 主题色 */
      cursor: pointer;
      font-size: 13px;
    }

    .page-btn:disabled {
      color: var(--el-color-info-light-3); /* Element Plus 禁用色 */
      cursor: not-allowed;
    }

    .page-info {
      font-size: 13px;
      color: var(--el-text-color-regular);
    }
  }
}
</style>
